
'''
-- 下发命令
CREATE TABLE device_command (

    id SERIAL PRIMARY KEY,
    create_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    -- 命令类型：1-设备控制，2-设备状态查询
    type VARCHAR(255) NOT NULL,
    -- 命令内容
    content VARCHAR(255) NOT NULL,
    -- 设备ID
    device_id INTEGER NOT NULL,

    CONSTRAINT fk_device_id
        FOREIGN KEY (device_id)
        REFERENCES devices (id)
        ON DELETE CASCADE
);

SELECT SETVAL('device_command_id_seq', (SELECT MAX(id) FROM device_command));


from . import logger

class DeviceCommandTable:

    def __init__(self, connection, cursor):

        self.connection = connection
        self.cursor = cursor

    # 创建设备命令
    def create_device_command(self, type, content, device_id):
    
        try:
            self.cursor.execute("INSERT INTO device_command (type, content, device_id) VALUES (%s, %s, %s) RETURNING id", (type, content, device_id))

        except Exception as e:
            logger.error("Error creating device command: {}".format(e))
            return False, str(e)

        else:
            logger.info(f"Device command created successfully.")
            return True, self.cursor.fetchone()["id"]
        
    # 获取设备命令
    def get_device_command(self, device_id, limit=5, offset=0):

        try:
            self.cursor.execute("SELECT * FROM device_command WHERE device_id = %s ORDER BY id DESC LIMIT %s OFFSET %s", (device_id, limit, offset))
            device_commands = self.cursor.fetchall()

        except Exception as e:
            logger.error("Error getting device command: {}".format(e))
            return False, str(e)

        else:
            logger.info(f"Device command retrieved successfully.")
            return True, device_commands
    
    # 获取所有设备命令
    def get_all_device_command(self, type=None, content=None, device_id=None, limit=10, offset=0):
        
        sql = "SELECT * FROM device_command"
        params = []

        if type:
            sql += " WHERE type = %s"
            params.append(type)

        if content:
    
            if not params:
                sql += " WHERE content = %s"
            else:
                sql += " AND content = %s"

            params.append(content)

        if device_id:
        
            if not params:
                sql += " WHERE device_id = %s"
            else:
                sql += " AND device_id = %s"

            params.append(device_id)

        sql += " ORDER BY id DESC LIMIT %s OFFSET %s"
        params.append(limit)
        params.append(offset)

        try:
            self.cursor.execute(sql, params)
            device_commands = self.cursor.fetchall()

        except Exception as e:
            logger.error("Error getting all device command: {}".format(e))
            return False, str(e)

        else:
            logger.info(f"All device command retrieved successfully.")
            return True, device_commands
        
    # 删除设备命令
    def delete_device_command(self, command_ids):
        
        try:
            self.cursor.execute("DELETE FROM device_command WHERE id IN %s", (tuple(command_ids),))
            self.connection.commit()

        except Exception as e:
            logger.error("Error deleting device command: {}".format(e))
            return False, str(e)

        else:
            logger.info(f"Device command {command_ids} deleted successfully.")
            return True, None


'''

from flask import Blueprint, request, jsonify, g

from db_utils.postgresql_connection import PostgreSQLConnection
from db_utils.repositories.device_command_table import DeviceCommandTable
from push_device_task import PushDeviceTask

import logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)

send_command_blueprint = Blueprint('send_command_blueprint', __name__)




@send_command_blueprint.route('/send_command', methods=['POST'])
def send_command():
    
    device_id = request.form.get('device_id')
    command_type = request.form.get('command_type', default="ischemic_pre_trainer")
    command_content = request.form.get('command_content')

    if not device_id or not command_type or not command_content:
        return jsonify({"status": -1, "errorCode": 1001, "errorMsg": "缺少参数", "resultBody": None})

    with PostgreSQLConnection() as (conn, cursor):
        device_command_table = DeviceCommandTable(conn, cursor)
        status, result = device_command_table.create_device_command(command_type, command_content, device_id)

    if not status:
        return jsonify({"status": -1, "errorCode": 1003, "errorMsg": result, "resultBody": None})
    else:

        # 推送命令消息到设备
        push_device_task = PushDeviceTask()

        print(f"device_id: {device_id}, command_type: {command_type}, command_content: {command_content}")

        status, error_msg = push_device_task.send_update_software_message_to_redis_by_id(device_id, command_content, command_type)
        
        if status:
            return jsonify({"status": 1, "errorCode": None, "errorMsg": None, "resultBody": {"id": result}})
        else:
            return jsonify({"status": -1, "errorCode": 1004, "errorMsg": error_msg, "resultBody": None})



# @send_command_blueprint.route('/send_command', methods=['POST'])
# def send_command():
    
#     device_id = request.form.get('device_id')
#     command_type = request.form.get('command_type', default="ischemic_pre_trainer")
#     command_content = request.form.get('command_content')

#     if not device_id or not command_type or not command_content:
#         return jsonify({"status": -1, "errorCode": 1001, "errorMsg": "缺少参数", "resultBody": None})

#     with PostgreSQLConnection() as (conn, cursor):
#         try:
#             device_command_table = DeviceCommandTable(conn, cursor)
#             status, result = device_command_table.create_device_command(command_type, command_content, device_id)

#         except Exception as e:
#             logger.error("Error creating device command: {}".format(e))
#             return jsonify({"status": -1, "errorCode": 1002, "errorMsg": str(e), "resultBody": None})

#         else:
#             if not status:
#                 return jsonify({"status": -1, "errorCode": 1003, "errorMsg": result, "resultBody": None})
#             else:
    
#                 # 推送命令消息到设备
#                 push_device_task = PushDeviceTask()

#                 print(f"device_id: {device_id}, command_type: {command_type}, command_content: {command_content}")

#                 status, error_msg = push_device_task.send_update_software_message_to_redis_by_id(device_id, command_content, command_type)
                
#                 if status:
#                     return jsonify({"status": 1, "errorCode": None, "errorMsg": None, "resultBody": {"id": result}})
#                 else:
#                     return jsonify({"status": -1, "errorCode": 1004, "errorMsg": error_msg, "resultBody": None})


@send_command_blueprint.route('/get_command_by_device_id', methods=['GET'])
def get_command_by_device_id():
    
    device_id = request.args.get('device_id')
    limit = request.args.get('limit', default=5, type=int)
    offset = request.args.get('offset', default=0, type=int)

    if not device_id:
        return jsonify({"status": -1, "errorCode": 1001, "errorMsg": "缺少参数", "resultBody": None})

    with PostgreSQLConnection() as (conn, cursor):
        try:
            device_command_table = DeviceCommandTable(conn, cursor)
            status, commands = device_command_table.get_device_command(device_id, limit, offset)
            _, count = device_command_table.count_device_command(device_id)

        except Exception as e:
            logger.error("Error getting command by device id: {}".format(e))
            return jsonify({"status": -1, "errorCode": 1002, "errorMsg": str(e), "resultBody": None})

        else:
            if status:
                return jsonify({"status": 1, "errorCode": None, "errorMsg": None, "resultBody": {"list": commands, "count": count}})
            else:
                return jsonify({"status": -1, "errorCode": 1003, "errorMsg": commands, "resultBody": None})


@send_command_blueprint.route('/get_all_command', methods=['GET'])
def get_all_command():
    
    command_type = request.args.get('command_type', default=None)
    command_content = request.args.get('command_content', default=None)
    device_id = request.args.get('device_id', default=None)
    limit = request.args.get('limit', default=10, type=int)
    offset = request.args.get('offset', default=0, type=int)

    with PostgreSQLConnection() as (conn, cursor):
        try:
            device_command_table = DeviceCommandTable(conn, cursor)
            status, commands = device_command_table.get_all_device_command(command_type, command_content, device_id, limit, offset)
            _, count = device_command_table.count_all_device_command(command_type, command_content, device_id)
        except Exception as e:
            logger.error("Error getting all command: {}".format(e))
            return jsonify({"status": -1, "errorCode": 1002, "errorMsg": str(e), "resultBody": None})

        else:
            if status:
                return jsonify({"status": 1, "errorCode": None, "errorMsg": None, "resultBody": {"list": commands, "count": count}})
            else:
                return jsonify({"status": -1, "errorCode": 1003, "errorMsg": commands, "resultBody": None})


@send_command_blueprint.route('/delete_command', methods=['POST'])
def delete_command():
    
    command_ids = request.form.getlist('command_ids[]')

    if not command_ids:
        return jsonify({"status": -1, "errorCode": 1001, "errorMsg": "缺少参数", "resultBody": None})

    with PostgreSQLConnection() as (conn, cursor):
        try:
            device_command_table = DeviceCommandTable(conn, cursor)
            status, result = device_command_table.delete_device_command(command_ids)

        except Exception as e:
            logger.error("Error deleting command: {}".format(e))
            return jsonify({"status": -1, "errorCode": 1002, "errorMsg": str(e), "resultBody": None})

        else:        
            if status:
                return jsonify({"status": 1, "errorCode": None, "errorMsg": None, "resultBody": None})
            else:
                return jsonify({"status": -1, "errorCode": 1003, "errorMsg": result, "resultBody": None})
